package com.bit.finance.loaders.estimatives;

import java.io.IOException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.bit.finance.data.Company;

public class YahooEstimatives {

	public static Company[] companies = null;
	private Document document = null;
	private Elements tables = null;

	public YahooEstimatives(String companySymbol) {
		Connection connection = Jsoup.connect("http://finance.yahoo.com/q/ae"); // ?s=bac+Analyst+Estimates
		connection.userAgent("Mozilla");
		connection.data("s", companySymbol + " Analyst Estimates");
		try {
			document = connection.get();
			tables = document.select("table.yfnc_tableout1");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public IEstimatedEarnings[] getEstimateEarnings() {
		IEstimatedEarnings result[] = new YahooEstimatedEarnings[4];
		Element table = tables.get(0);
		byte collumnCounter = 0;
		for (Element htmlNode : table.select("th:matches([0-9]$)")) {
			String dateString = htmlNode.text();
			String theTextEventData[] = dateString.split(" ");
			result[collumnCounter] = new YahooEstimatedEarnings();
			try {
				result[collumnCounter++].setEventDate(new SimpleDateFormat(
						"dd/MMM/yy").parse("01/" + theTextEventData[2] + "/"
						+ theTextEventData[3]));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		byte paramCounter = -1;
		NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
		for (Element htmlNode : table.select("tr")) {
			paramCounter++;
			collumnCounter = 0;
			for (Element td : htmlNode.select("td.yfnc_tabledata1")) {
				try {
					switch (paramCounter) {
					case 1:
						result[collumnCounter++].setAvgEstimate(nf.parse(
								td.text()).doubleValue());
						break;
					case 2:
						result[collumnCounter++]
								.setNumberOfAnalysts(nf.parse(td.text()).intValue());
						break;
					case 3:
						result[collumnCounter++].setLowEstimate(nf.parse(td
								.text()).doubleValue());
						break;
					case 4:
						result[collumnCounter++].setHighEstimate(nf.parse(td
								.text()).doubleValue());
						break;
					case 5:
						result[collumnCounter++].setYearAgoEPS(nf.parse(td
								.text()).doubleValue());
						break;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}

			}
		}

		return result;
	}
}
